package com.ikangtai.shecare.stickycalendar.http;

import android.content.Context;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.stickycalendar.http.util.LHValueMsg;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ikangtai on 2016/9/1.
 */
public class LHValueHttp {

    private Context context;
    private static DBManager dbManager;
    private List<LHValueMsg> lhValueMsgList;
    public UserRecordData userRecordData = new UserRecordData();
    private String dateRecord; // 具体某天的时间

    public LHValueHttp(Context context,List<LHValueMsg> lhValueMsgList){
        this.context = context;
        this.lhValueMsgList = lhValueMsgList;
        dbManager = new DBManager(context);
        EventBus.getDefault().register(this);

        dateRecord = lhValueMsgList.get(0).getDateRecord(); // 时间
        userRecordData = dbManager.getSelectedDayRecordData(App.userName, dateRecord);
        userRecordData.setId(userRecordData.getId());
    }

    public void saveSelectedDayRecord() {
        long currentTime = DateUtil.getStringToDate(DateUtil.getCurrentDay() + " 00:00:00");
        long recordDateZeroTime = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        if (recordDateZeroTime > currentTime) {
            Toast.makeText(context, R.string.edit_record_information_future, Toast.LENGTH_SHORT).show();
            return;
        }

        uploadRecordInfo();
    }

    private void getRecordInfo() {
        if ("".equals(userRecordData.getId()) || null == userRecordData.getId()) {
            userRecordData.setId(UUID.randomUUID().toString());
        }

        userRecordData.setUserName(App.userName);

        if (0 == userRecordData.getRecordDate()) {
            userRecordData.setRecordDate(DateUtil.getStringToDate(dateRecord + " 12:00:00"));
        } else {
            userRecordData.setRecordEditDate(new Date().getTime() / 1000);
        }

        userRecordData.setLHResult(lhValueMsgList.get(0).getLHResult());
    }

    private void uploadRecordInfo() {
        getRecordInfo();

        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        String appendUrl = "gyna/replaceLHMsg.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("LHPaperID", userRecordData.getId());
            okHttpClient.add("LHDate", "" + DateUtil.getDateTimeStr2bit(userRecordData.getRecordDate()));
            okHttpClient.add("LHResult", userRecordData.getLHResult());
            AppLog.i("wzz------userRecordData.getLHResult()----"+userRecordData.getLHResult());
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    AppLog.i("save has sex onResponse failed!");
                    saveRecordData(0);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        AppLog.i("wzz------respCode----"+respCode);
                        if (App.HTTP_RESP_OK == respCode) {
                            saveRecordData(1);
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            uploadRecordInfo();
                        } else {
                            saveRecordData(0);
                        }
                    } catch (JSONException e) {
                        AppLog.i("save has sex onResponse failed!");
                        e.printStackTrace();
                        saveRecordData(0);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("save has sex onResponse failed!");
            e.printStackTrace();
            saveRecordData(0);
        }
    }

    private void saveRecordData(int isSynced) {
        userRecordData.setIsSynced(isSynced);
        dbManager.saveRecordData(userRecordData);
    }

}
